<?php
    function processing($data)
    {        
        $IpCall = getRealIpAddr();        
                
        $regx_cai = "/^" . $data["syntax_code_db"] . "(\s+)(\d+)(\s+)([a-zA-Z0-9]{1,})$/si";                
        $regx_tang = "/^" . $data["syntax_code_db"] . "(\s+)(\d+)(\s+)([a-zA-Z0-9]{1,})(\s+)([0-9]{1,})$/si";                

        $response["mobile"] = "";
        
        if(preg_match($regx_cai, $data["content"]) || preg_match($regx_tang, $data["content"])){
            
            if(preg_match($regx_cai, $data["content"])){
                $syntax = buildSyntax($data["content"], $regx_cai);                                    
            } else {
                $syntax = buildSyntaxTang($data["content"], $regx_tang);                    
                $response["mobile"] = $syntax["mobile"];                
            }
            
            $list_service_code = array($data["service_code_db"]);
            
            $data["userId"] = $syntax["userId"];
            $data["id"] = $syntax["ringId"];
            
            if(in_array($data["serviceCode"], $list_service_code)){
              
                /* lấy mã nhạc chờ tương ứng */
                $telco = checkTelco($data["sender"]);                
                
                $ring = getRing($data["id"], $telco);
                
                if(!empty($ring)){
                    $key = array_rand($ring);
                    
                    $response["status"] = 1;        
                    $response["code"] = trim($ring[$key]["code"]);
                    $data["status"] = 1;
                    
                    /* Cập nhật lượt download */
                    if($IpCall!="101.99.14.24") UpdateDownload($data["id"]);
                } else {
                    $response["status"] = 0;                        
                    $response["code"] = "";                
                    
                    $data["status"] = 0;
                }                                
            } else {
                
                $response["status"] = 0;                        
                $response["code"] = "";                
                
                $data["status"] = 0;                 
            }               
                
        } else {
            $response["status"] = 0;                
            $response["code"] = "";                
            
            $data["userId"] = 0;                
            $data["status"] = 0;    
            
            $data["id"] = 0;
        }
        
        /* log sms */        
        $data["telco"] = checkTelco($data["sender"]);    
        $data["price"] = priceServiceCode($data["serviceCode"]);    
        $data["partnerId"] = 1; //ID partner HDC    
        $data["type"] = 4; //Thể loại nhạc chờ   
        
        if(!empty($response["mobile"])){
            $data["output"] = $response["status"] . "|" . $data["transactionId"] . "|" . $response["code"] . "|" . $response["mobile"];    
        } else {
            $data["output"] = $response["status"] . "|" . $data["transactionId"] . "|" . $response["code"];    
        }        
        
                
        if($IpCall=="101.99.14.24"){
            $result = InsertSmsLogTest($data);       
        } else {
            $result = InsertSmsLog($data);    
        }
        
        return $response;
    }
    
    function CheckTransaction($transactionId)
    {
        $sql = "SELECT count(id) FROM c_sms_log_test WHERE `transactionId`='" . mysql_escape_string($transactionId) . "'";
        $result = @mysql_query($sql);    
        $rows = @mysql_fetch_assoc($result);        
        return $rows["count(id)"];
    }
    
    function UpdateDownload($id)
    {
        $sql = "UPDATE c_ring_back SET download=(download+1) WHERE id=" . $id;
        $result = @mysql_query($sql);            
        return $result;
    }
    
    function getUser($refCode)
    {
        $sql = "SELECT id FROM c_user WHERE `refCode`='" . mysql_escape_string($refCode) . "'";
        $result = @mysql_query($sql);    
        $rows = @mysql_fetch_assoc($result);        
        return $rows;   
    }
    
    function getRing($ringId, $telco)
    {
        $sql = "SELECT code FROM c_ring_code WHERE `ringId`='" . mysql_escape_string($ringId) . "' AND telco='" . mysql_escape_string($telco) . "'";
        $result = @mysql_query($sql);        
        $rows = array();
        while($row = @mysql_fetch_assoc($result)){
            $rows[] = $row;
        }
        
        return $rows;    
    }
    
    function InsertSmsLog($data)
    {
        $sql = "INSERT INTO c_sms_log SET 
            `userId`='" . mysql_escape_string($data["userId"]) . "'
            , `partnerId`=" . mysql_escape_string($data["partnerId"]) . "
            , `type`=" . mysql_escape_string($data["type"]) . "
            , `dataId`=" . mysql_escape_string($data["id"]) . "
            , `content`='" . mysql_escape_string($data["content"]) . "'
            , `output`='" . mysql_escape_string($data["output"]) . "'
            , `sender`='" . mysql_escape_string($data["sender"]) . "'
            , `telco`='" . mysql_escape_string($data["telco"]) . "'
            , `serviceCode`=" . mysql_escape_string($data["serviceCode"]) . "
            , `price`=" . mysql_escape_string($data["price"]) . "
            , `status`=" . mysql_escape_string($data["status"]) . "
            , `transactionId`=" . mysql_escape_string($data["transactionId"]) . "
            , `day`=" . date("d") . "
            , `month`=" . date("m") . "
            , `year`=" . date("Y") . "
            , `create_date`=" . time() . "            
        ";        
        
        $result = @mysql_query($sql);
        return $result;    
    }
    
    function InsertSmsLogTest($data)
    {
        $sql = "INSERT INTO c_sms_log_test SET 
            `userId`='" . mysql_escape_string($data["userId"]) . "'
            , `partnerId`=" . mysql_escape_string($data["partnerId"]) . "
            , `type`=" . mysql_escape_string($data["type"]) . "
            , `dataId`=" . mysql_escape_string($data["id"]) . "
            , `content`='" . mysql_escape_string($data["content"]) . "'
            , `output`='" . mysql_escape_string($data["output"]) . "'
            , `sender`='" . mysql_escape_string($data["sender"]) . "'
            , `telco`='" . mysql_escape_string($data["telco"]) . "'
            , `serviceCode`=" . mysql_escape_string($data["serviceCode"]) . "
            , `price`=" . mysql_escape_string($data["price"]) . "
            , `status`=" . mysql_escape_string($data["status"]) . "
            , `transactionId`=" . mysql_escape_string($data["transactionId"]) . "
            , `day`=" . date("d") . "
            , `month`=" . date("m") . "
            , `year`=" . date("Y") . "
            , `create_date`=" . time() . "            
        ";        
        
        $result = @mysql_query($sql);
        return $result;    
    }
    
    function buildSyntax($content, $regx)
    {
        preg_match($regx, $content, $match);        
        $ringId = !empty($match[2]) ? $match[2] : 0;
        $refCode = !empty($match[4]) ? $match[4] : "";
        
        
        /* 
        * Kiểm tra user có tồn tại không
        * Không tồn tại thì trả về 0
        */
        
        $user = getUser($refCode);
        
        $result = array();
        $result["userId"] = !empty($user) ? $user["id"] : 0;
        $result["ringId"] = $ringId;
        
        return $result;
    }
    
    function buildSyntaxTang($content, $regx)
    {
        preg_match($regx, $content, $match);        
        $ringId = !empty($match[2]) ? $match[2] : 0;
        $refCode = !empty($match[4]) ? $match[4] : "";
        $mobile = !empty($match[6]) ? $match[6] : "";
        
        
        /* 
        * Kiểm tra user có tồn tại không
        * Không tồn tại thì trả về 0
        */
        
        $user = getUser($refCode);
        
        $result = array();
        $result["userId"] = !empty($user) ? $user["id"] : 0;
        $result["ringId"] = $ringId;
        $result["mobile"] = $mobile;
        
        $first = substr($result["mobile"], 0, 1);
        if($first=="0"){
            $result["mobile"] = substr($result["mobile"], 1, strlen($result["mobile"]) - 1);
        } else if($first="8"){
            $result["mobile"] = substr($result["mobile"], 2, strlen($result["mobile"]) - 2);
        }
        
        $result["mobile"] = "84" . $result["mobile"];
        
        return $result;
    }
    
    function checkTelco($mobile)
    {        
        $first = substr($mobile, 0, 1);
        if($first=="0"){
            $mobile = substr($mobile, 1, strlen($mobile) - 1);
        } else if($first="8"){
            $mobile = substr($mobile, 2, strlen($mobile) - 2);
        }
        
        $mobile = "84" . $mobile;
        
        $patternViettel = "/^84(9[678]|16[2-9])[\d]{7}/";
        $patternMobi = "/^84(9[03]|12[01268])[\d]{7}/";
        $patternVina = "/^84(9[14]|12[34579])[\d]{7}/";
        $patternVnmobile = "/^84(9[2]|18[86])[\d]{7}/";
        $patternBeeline = "/^84(9[9]|19[9])[\d]{7}/";
        
        if(preg_match($patternViettel, $mobile)){
            $telco = "1";    
        } else if(preg_match($patternMobi, $mobile)){
            $telco = "2";
        } else if(preg_match($patternVina, $mobile)){
            $telco = "3";
        } else if(preg_match($patternVnmobile, $mobile)){
            $telco = "4";
        } else if(preg_match($patternBeeline, $mobile)){
            $telco = "5";
        } else {
            $telco = "0";
        }
        
        return $telco;    
    }
    
    function priceServiceCode($serviceCode)
    {
        $pattern_0 = "/^(\d)0(\d)(\d)$/si";
        $pattern_1 = "/^(\d)1(\d)(\d)$/si";
        $pattern_2 = "/^(\d)2(\d)(\d)$/si";
        $pattern_3 = "/^(\d)3(\d)(\d)$/si";
        $pattern_4 = "/^(\d)4(\d)(\d)$/si";
        $pattern_5 = "/^(\d)5(\d)(\d)$/si";
        $pattern_6 = "/^(\d)6(\d)(\d)$/si";        
        $pattern_7 = "/^(\d)7(\d)(\d)$/si";        
        
        $price = 0;
        if(preg_match($pattern_0, $serviceCode)){
            $price = 500;    
        } else if(preg_match($pattern_1, $serviceCode)){
            $price = 1000;    
        } else if(preg_match($pattern_2, $serviceCode)){
            $price = 2000;    
        } else if(preg_match($pattern_3, $serviceCode)){
            $price = 3000;    
        } else if(preg_match($pattern_4, $serviceCode)){
            $price = 4000;    
        } else if(preg_match($pattern_5, $serviceCode)){
            $price = 5000;    
        } else if(preg_match($pattern_6, $serviceCode)){
            $price = 10000;    
        } else if(preg_match($pattern_7, $serviceCode)){
            $price = 15000;    
        } 
        return $price;
    }
    
    function getRealIpAddr()
    {
        if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
        {
            $ip=$_SERVER['HTTP_CLIENT_IP'];
        }
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
        {
            $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        else
        {
            $ip=$_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }  
    
    function IpPublic()
    {
        $ip = array(
            "210.211.97.3"
            , "210.211.97.5"
            , "210.211.97.7"                                    
            , "210.211.97.14"                        
            , "210.211.97.18"                        
            , "101.99.14.24"                        
            , "127.0.0.1"                        
        );
        return $ip;
    }
    
    function getSmsSyntax()
    {
        $sql = "SELECT syntax FROM c_config_sms";
        $result = @mysql_query($sql);
        $rows = array();    
        while($row = @mysql_fetch_assoc($result)){
            $rows[] = $row;    
        }
        
        return $rows;   
    }
    
    function getTypeSyntax($syntax_code)
    {
        $sql = "SELECT type, serviceCode FROM c_config_sms WHERE `syntax`='" . mysql_escape_string($syntax_code) . "'";
        $result = @mysql_query($sql);
        $rows = @mysql_fetch_assoc($result);
        return $rows;   
    }
?>
